package com.miaoyi.redisdemo.controller;

import com.miaoyi.redisdemo.entity.WxLotteryPrize;
import com.miaoyi.redisdemo.service.WxLotteryPrizeService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import constans.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/redis")
@Api(value = "RedissonController", tags = "活动共用类")
public class RedissonController {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Resource
    private RedissonClient redissonClient;
    @Autowired
    private WxLotteryPrizeService lotteryPrizeService;


    @GetMapping("redissonput")
    @ApiOperation("redissonput")
    public R redissonput() throws InterruptedException {

        //获取锁(可重入)，指定锁的名称
        RLock lock = redissonClient.getLock("anyLock:" + "13536477084");
        //boolean isLock = lock.tryLock();//获取不到就算了
       // boolean isLock = lock.tryLock();
        boolean isLock = lock.tryLock(1,4,TimeUnit.SECONDS);

        //判断获取锁成功
        if (isLock) {
            try {
                //lock.lock(4,TimeUnit.SECONDS);//一直阻塞等待
                Thread.sleep(35000);
                System.out.println("进来："+Thread.currentThread().getId());
                int count = lotteryPrizeService.count(Wrappers.lambdaQuery(WxLotteryPrize.class)
                        .eq(WxLotteryPrize::getActId, "66"));
                if (count > 0) {
                    return R.failed();
                }
                WxLotteryPrize wxLotteryPrize = new WxLotteryPrize();
                wxLotteryPrize.setActId("66");
                lotteryPrizeService.save(wxLotteryPrize);
                return R.ok();

            } finally {
                //释放锁
                lock.unlock();
            }
        }
        return R.failed();
    }


    @GetMapping("browse2")
    @ApiOperation("查询全部用户操作")
    public Object browse(@RequestParam String phone) {
        //获取锁(可重入)，指定锁的名称
        RLock lock = redissonClient.getLock("anyLock:" + phone);
        //尝试获取锁，参数分别是：获取锁的最大等待时间(期间会重试)，锁自动释放时间，时间单位
        //boolean isLock = lock.tryLock(1,10, TimeUnit.SECONDS);
        boolean isLock = lock.tryLock();//获取不到就算了
        //判断获取锁成功
        if (isLock) {
            try {
                Thread.sleep(2000);
                System.out.println("执行业务");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                //释放锁
                lock.unlock();
            }
        } else {
            System.out.println("获取不到");
        }

        return R.ok("12");
    }


}
